// <!--引入store，用于管理socket推送来的消息-->
import store from '@/store';
import { iotLogupdate } from "@/api/bedList";
import Vue from "vue";
import { parseTime } from "@/utils";
// <!--封装websocket对象-->
const WS = {
    $ws:null, // webscoket实例
    wsUrl: 'wss://device.yiyanglao.com.cn:9002', // websocket链接地址
    // 初始化webSocket
    createWS: function(){
          let that = this;
          try {
            if ("WebSocket" in window) {
              that.$ws = new WebSocket(that.wsUrl)
            } else if ("MozWebSocket" in window) {
              that.$ws = new MozWebSocket(that.wsURl);
            }
            that.$ws.onopen = that.wsOpen
            that.$ws.onmessage = that.wsMessage
            that.$ws.onerror = that.wsError
            that.$ws.onclose = that.wsClose
          } catch (e) {
          }
        // if ("WebSocket" in window) {
        //   this.$ws = new WebSocket(this.wsURl)
        // } else if ("MozWebSocket" in window) {
        //   that.$ws = new MozWebSocket(this.wsURl);
        //   this.$ws.onopen = this.wsOpen
        //   this.$ws.onmessage = this.wsMessage
        //   this.$ws.onerror = this.wsError
        //   this.$ws.onclose = this.wsClose
        // } else {
        //    console.log('当前浏览器不支持webSocket')
        // }
    },
    // <!--webSocket 打开-->
    wsOpen: function() {
        console.log('== websocket open ==')
        // <!--开始心跳-->
        heartBeat.start()
    },
    // <!--websocket 接收到服务器消息-->
    wsMessage:function(msg) {
        let that = this;
        // <!--接受到消息，重置心跳-->
        // heartBeat.reset()
        // console.log(msg)
         const data = JSON.parse(msg.data)
        if (data.route == 'face') {
          store.dispatch('facewebsocket/setDeviceMsg', data)
          Vue.prototype.$ws.faceInit(data, Vue.prototype)
        } else {
          store.commit('websocket/SET_WS_MSG', msg.data)
          //处理设备报警信息
          Vue.prototype.$ws.init(msg, Vue.prototype);
        }
    },
    // <!--websocket 发生错误-->
    wsError: function(err){
        console.log('== websocket error ==', err)
    },
    // <!--websocket 关闭连接-->
    wsClose: function(event){
        console.log('== websocket close ==', this.$ws)
        // this.$ws.close();
        if(this.$ws) {
          this.$ws.close();
        } else {
          this.close();
        }
    },
    // facewebsocket  处理报警信息
    faceInit: function (data, _that) {
      if (data.route == 'device_warning') {
        const res = data.data
        _that.$notice({
          message: res.msg,
          address: res.location + '-' + res.dev_name,
          time: utils.parseTime(res.time),
          duration: 0
        })
        let { notice_num } = store.state.d2admin.websocket
        const num = notice_num + 1
        store.dispatch('websocket/setNoticeNum', num)
      }
    },
    //处理报警信息
    init: function(res, _that) {
      let result = eval("(" + res.data + ")");
      if(!result){
        return false
      }
      if(result.route == 'device_warning' || result.route == 'box_device_warning') {
        let data = result.data;
        //报警器报警
        if(data.type == 2) {
          let location = "";
          if(data.location) {
          	location = "请注意查看，"+ data.location +"间报警器报警";
          } else {
          	location = "请注意查看，房间报警器报警";
          }
          _that.$notice({
            message: "房间报警器报警",
            address: location,
            time: parseTime(data.time),
            duration: 0,
            onClick: () => {
              data.log_id && iotLogupdate("get", {id: data.log_id})
            }
          })
        }

        //门磁报警
        if(data.type == 3) {
          let location = "";
          if(data.status == "on") {
            if(data.location) {
            	location = "请注意查看，"+ data.location +"间门打开";
            } else {
            	location = "请注意查看，卫生间门打开";
            }
          } else {
            if(data.location) {
            	location = data.location + "门关闭";
            } else {
            	location = "卫生间门关闭";
            }
          }

          _that.$notice({
            message: "卫生间门状态",
            address: location,
            time: parseTime(data.time),
            duration: 0,
            onClick: () => {
              data.log_id && iotLogupdate("get", {id: data.log_id})
            }
          })
        }

        //燃气报警器
        if(data.type == 4) {
          let location = "";
          if(data.location) {
          	location = data.location +"可燃气体报警";
          } else {
          	location = "请注意查看，房间可燃气体报警";
          }
          _that.$notice({
            message: "可燃气体报警",
            address: location,
            time: parseTime(data.time),
            duration: 0,
            onClick: () => {
              data.log_id && iotLogupdate("get", {id: data.log_id})
            }
          })
        }

        //人体红外传感器
        if(data.type == 5) {
          let location = "";
          if(data.status == 1) {
            if(data.location) {
            	location = "请注意查看，"+  data.location +"有人";
            } else {
            	location = "请注意查看，有人进入卫生间";
            }
          } else {
            if(data.location) {
            	location = data.location +"无人";
            } else {
            	location = "请注意查看，卫生间无人";
            }
          }

          _that.$notice({
            message: "卫生间检测状态",
            address: location,
            time: parseTime(data.time),
            duration: 0,
            onClick: () => {
              data.log_id && iotLogupdate("get", {id: data.log_id})
            }
          })
        }

        //烟雾报警器
        if(data.type == 6) {
          let location = "";
          if(data.location) {
          	location = "请注意查看，"+ data.location +" 烟雾报警";
          } else {
          	location = "请注意查看，房间烟雾报警";
          }
          _that.$notice({
            message: "烟雾报警",
            address: location,
            time: parseTime(data.time),
            duration: 0,
            onClick: () => {
              data.log_id && iotLogupdate("get", {id: data.log_id})
            }
          })
        }

        //漏水
        if(data.type == 8) {
          let location = "";
          if(data.location) {
          	location = "请注意查看，"+ data.location +"漏水报警";
          } else {
          	location = "请注意查看，房间漏水报警";
          }
          _that.$notice({
            message: "漏水报警",
            address: location,
            time: parseTime(data.time),
            duration: 0,
            onClick: () => {
              data.log_id && iotLogupdate("get", {id: data.log_id})
            }
          })
        }

        //安防
        if(data.type == 10) {
          let location = "";
          if(data.location) {
          	location = "请注意查看，"+ data.location +"安防报警";
          } else {
          	location = "请注意查看，安防报警";
          }
          _that.$notice({
            message: "安防报警",
            address: location || "安防报警",
            time: parseTime(data.time),
            duration: 0,
            onClick: () => {
              data.log_id && iotLogupdate("get", {id: data.log_id})
            }
          })
        }

        //离床
        if(data.type == 11) {
          data.status.forEach(function(item) {
          	if(item.id == 1) {
          		//在床
              let location = "";
              if(item.value == 0) {
              	location = "";
              } else { //离床
              	location = "请注意查看，"+ data.location +"离床报警";
              }
          		if (location != "") {
                _that.$notice({
                  message: "离床报警",
                  address: location || "离床报警",
                  time: parseTime(data.time),
                  duration: 0,
                  onClick: () => {
                    data.log_id && iotLogupdate("get", {id: data.log_id})
                  }
                })
          		}
          	}
          	if(item.id == 2) {
          		//未尿床
          		let location = "";
          		if(item.value == 0) {
          			location = "";
          		} else { //尿湿
          			location = "请注意查看，"+ data.location +"尿湿报警";
          			if (location != ""){
                  _that.$notice({
                    message: "尿湿报警",
                    address: location || "尿湿报警",
                    time: parseTime(data.time),
                    duration: 0,
                    onClick: () => {
                      data.log_id && iotLogupdate("get", {id: data.log_id})
                    }
                  })
          			}
          		}
          	}
          })
        }

        if(data.type == 12) {
        	data.status.forEach(function(item) {
        		if(item.id == 2) {
        			//未尿床
        			let location = "";
        			if(item.value == 0) {
        				location = "";
        			} else { //尿湿
        				location = "请注意查看，"+ data.location +"尿湿报警";
        				if (location != ""){
        					_that.$notice({
        					  message: "尿湿报警",
        					  address: location || "尿湿报警",
        					  time: parseTime(data.time),
        					  duration: 0,
        					  onClick: () => {
        					    data.log_id && iotLogupdate("get", {id: data.log_id})
        					  }
        					})
        				}
        			}
        		}
        	})
        }
      }

    }
}
// <!--webSocket 心跳-->
const heartBeat = {
    timeout: 30000, // 心跳重连时间
    timeoutObj:null, // 定时器
    reset:function(){
        clearInterVal(this.timeoutObj)
        console.log('websocket 心跳')
        WS.start()
    },
    start:function(){
        // this.timeoutObj = setTimeout(function(){
        //     if(WS.$ws.readyState === 1){
        //       // var userinfo = localStorage.getItem("userdata") || {}
        //       // if(userinfo) {
        //       // 	userinfo = JSON.parse(userinfo)
        //       // }
        //       // var data = {
        //       // 	 'user_id': userinfo && (userinfo.uid + '-' + Math.floor(Math.random() * 10))  || "888-2",
        //       // 	 'iid': 1,
        //       // };
        //       // var msg = {
        //       //     'controller_name':'RoomController',
        //       //     'method_name':'bangding',
        //       //     'data':data
        //       // };
        //       // WS.$ws.send(JSON.stringify(msg))
        //     }
        // },this.timeout)
        let userinfo = localStorage.getItem("userdata") || {}
        if(userinfo) {
        	userinfo = JSON.parse(userinfo)
        }
        let data = {
        	 'user_id': userinfo && (userinfo.uid + '-' + Math.floor(Math.random() * 10))  || "888-2",
        	 'iid': userinfo.iid,
        };
        let msg = {
            'controller_name':'RoomController',
            'method_name':'bangding',
            'data':data
        };
        console.log(WS.$ws)
        if(WS.$ws && WS.$ws.readyState === 1) {
          WS.$ws.send(JSON.stringify(msg))
        }
    }
}
export default WS
